<template>
  <div class="w-full">
    <div class="flex items-center justify-between mb-2">
      <h2 class="text-2xl font-bold text-text-primary my-6">推荐影片</h2>
      <!-- <Button variant="ghost" size="sm">查看更多</Button> -->
    </div>
    <div :class="`movie-grid gap-4 ${gridColsClass}`">
      <div
        v-for="movie in movies"
        :key="movie.id"
      >
        <MovieCard
          :cover-url="movie.coverUrl"
          :title="movie.title"
          :rating="movie.rating"
          :tags="movie.tags"
          :is-ai="movie.isAi"
          :show-tags="true"
          @click="goDetail(movie.id)"
        />
      </div>
    </div>
    <div ref="loadMoreRef" class="flex justify-center mt-6">
      <UiButton v-if="!isLoading && hasMore" variant="secondary" size="md" @click="loadMore">加载更多</UiButton>
      <span v-else-if="isLoading" class="text-text-muted">加载中...</span>
      <span v-else-if="!hasMore" class="text-text-muted">没有更多内容了</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useDebounceFn } from '@vueuse/core'
import { useUiStore } from '../../store/useUiStore'
import { storeToRefs } from 'pinia'
import MovieCard from './MovieCard.vue'
import { useMovieLoader } from '../../composables/movies'
import { UiButton } from '../ui'

// Props
interface Props {
  initialMovies: any[]
}

const props = withDefaults(defineProps<Props>(), {
  initialMovies: () => []
})

const router = useRouter()
const uiStore = useUiStore()
const { currentColumns, gridColsClass } = storeToRefs(uiStore)
const { loadMovies, isLoading, hasMore, resetLoader } = useMovieLoader()
const movies = ref<any[]>([])
const loadMoreRef = ref<HTMLElement | null>(null)
const currentOffset = ref(0)

const goDetail = (id: number) => {
  console.log('MovieMasonry: 点击电影卡片，ID:', id)
  router.push({ name: 'MovieDetail', params: { id } })
}

let observer: IntersectionObserver | null = null

const loadMore = async () => {
  if (isLoading.value || !hasMore.value) return
  
  console.log('MovieMasonry: 开始加载更多，当前offset:', currentOffset.value)
  const newMovies = await loadMovies(currentColumns.value, 'masonry', currentOffset.value)
  console.log('MovieMasonry: 加载到的新电影:', newMovies)
  console.log('MovieMasonry: 新电影ID列表:', newMovies.map(m => m.id))
  
  if (newMovies.length > 0) {
    // 检查是否有重复数据
    const existingIds = new Set(movies.value.map(m => m.id))
    const uniqueNewMovies = newMovies.filter(m => !existingIds.has(m.id))
    
    console.log('MovieMasonry: 过滤后的唯一新电影数量:', uniqueNewMovies.length)
    
    if (uniqueNewMovies.length > 0) {
      movies.value.push(...uniqueNewMovies)
      currentOffset.value += newMovies.length
    } else {
      console.log('MovieMasonry: 没有新的唯一电影，停止加载')
      hasMore.value = false
    }
  } else {
    hasMore.value = false
  }
}

// 初始化电影数据
const initializeMovies = () => {
  console.log('MovieMasonry: 初始化电影数据')
  console.log('初始电影数量:', props.initialMovies.length)
  console.log('初始电影数据:', props.initialMovies)
  console.log('初始电影ID列表:', props.initialMovies.map(m => m.id))
  
  movies.value = [...props.initialMovies]
  currentOffset.value = props.initialMovies.length
  
  console.log('设置后的电影数量:', movies.value.length)
  console.log('设置后的电影数据:', movies.value)
  console.log('设置后的电影ID列表:', movies.value.map(m => m.id))
}

// 监听初始电影数据变化
watch(() => props.initialMovies, () => {
  initializeMovies()
}, { immediate: true })

onMounted(() => {
  // 设置无限滚动
  observer = new window.IntersectionObserver((entries) => {
    if (entries[0].isIntersecting && hasMore.value && !isLoading.value) {
      loadMore()
    }
  }, { threshold: 0.1 })
  
  if (loadMoreRef.value) observer.observe(loadMoreRef.value)
})

onUnmounted(() => {
  observer?.disconnect()
})
</script>